﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using DietPlanning.Models;

namespace DietPlanning.Controllers
{
    public class AccountController : Controller
    {
        private DailyFoodEntities db = new DailyFoodEntities();
        public static UserDietModels UserDiet = new UserDietModels();
        //
        // GET: /Account/LogOn

        public ActionResult Index()
        {
            var userId = Int32.Parse(Session["userId"].ToString());
            UserDiet.User = db.Users.First(o => o.UserID == userId);
            UserDiet.GetInfo();
            return View(UserDiet);
        }

        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(User model)
        {
            try
            {
                var cus = db.Users.First(o => o.Email == model.Email && o.Password == model.Password);
                UserDiet.User = cus;
                UserDiet.GetInfo();
                Session["UserId"] = cus.UserID;
                Session["UserName"] = cus.Name;
                if (cus != null && cus.Role == "Admin")
                {
                    //remember me
                    FormsAuthentication.SetAuthCookie(model.Email, true);
                    //Admin page
                    return RedirectToAction("Index", "User");
                }
                else if (cus != null && cus.Role == "Customer")
                {
                    FormsAuthentication.SetAuthCookie(model.Email, true);
                    return RedirectToAction("Index", "Account");
                }
                else
                {
                    return View(model);
                }
            }
            catch (Exception ex)
            {
                return View();
            }

        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(User model)
        {
            if (ModelState.IsValid)
            {
                model.Role = "Customer";
                db.Users.AddObject(model);
                db.SaveChanges();
                var newAccount = db.Users.First(o => o.Email == model.Email);
                UserDiet.User = newAccount;
                FormsAuthentication.SetAuthCookie(model.Email, false /* createPersistentCookie */);

                return RedirectToAction("AccountDetail");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }


        //
        // GET: /Account/AddMoreInfo
        public ActionResult AccountDetail()
        {
            return View(UserDiet.User);
        }

        //
        // POST: /Account/Register
        [HttpPost]
        public ActionResult AccountDetail(User model)
        {

            if (ModelState.IsValid)
            {
                db.Users.Attach(model);
                db.ObjectStateManager.ChangeObjectState(model, EntityState.Modified);
                db.SaveChanges();

                //Get new user + ID
                UserDiet.User = model;
                //Calculator Calory, Create default Diet
                UserDiet.CreateDietDefault();
                return RedirectToAction("Recommended");
                //return RedirectToAction("Recommended", new { id = model.UserID });
            }
            return View(model);
        }

        //Get
        public ActionResult Recommended()
        {
            var userId = Int32.Parse(Session["userId"].ToString());
            UserDiet.User = db.Users.First(o => o.UserID == userId);
            UserDiet.GetInfo();
            //UserDiet.CreateDietDefault();
            // *Need fix
            var diet = UserDiet.Diet.FirstOrDefault(o => o.UserID == UserDiet.User.UserID && o.isNew == 1);
            return View(diet);
        }

        //Post
        [HttpPost]
        public ActionResult Recommended(Diet newDiet)
        {
            if (ModelState.IsValid)
            {
                //foreach (var diet1 in UserDiet.Diet)
                //{
                //    //Change New to Old
                //    if (diet1.isNew == 1 && diet1.UserID == UserDiet.User.UserID)
                //    {
                //        db.Diets.First(o => o.DietID == diet1.DietID).isNew = 0;
                //        db.SaveChanges();
                //    }
                //}
                ////New Diet
                //newDiet.UserID = UserDiet.User.UserID;
                //newDiet.isNew = 1;
                //db.Diets.AddObject(newDiet);
                //db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View();
        }

        //public ActionResult DietDetail(int id)
        //{
        //    UserDiet.DietDetail = db.DietDetails.Where(o => o.DietID == id).ToList();
        //    return View(UserDiet);
        //    //return RedirectToAction("Index");

        //}

        public ActionResult DietDetail(int id, int day)
        {
            UserDiet.DietDetail = db.DietDetails.Where(o => o.DietID == id).ToList();
            UserDiet.ViewDays = day;
            return View(UserDiet);
            //return RedirectToAction("Index");

        }

        public ActionResult CreateDiet()
        {
            return View();

        }


        [HttpPost]
        public ActionResult CreateDiet(Diet diet)
        {
            var userId = Int32.Parse(Session["userId"].ToString());
            UserDiet.User = db.Users.First(o => o.UserID == userId);
            UserDiet.GetInfo();
            UserDiet.ChangeNewToOld();
            diet.UserID = UserDiet.User.UserID;
            diet.isNew = 1;
            int dietId = UserDiet.CreateDietCustom(diet);
            UserDiet.GetInfo();
            return RedirectToAction("DietDetail", new { id = dietId, day = 0 });
        }

        public ActionResult ViewFood(int dishId)
        {
            //List<Food> listFood = new List<Food>();
            //var foodlist = db.DishDetails.Where(o => o.DishID == dishId).ToList();
            //foreach (var dietDetail in foodlist)
            //{
            //    listFood.Add(db.Foods.Single(o => o.FoodID == dietDetail.FoodID));
            //}
            return View(db.Dishes.Where(o=>o.DishID==dishId));
        }



        #region no use

        // GET: /Account/ChangePassword
        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }
        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
        #endregion
    }
}
